package user

import (
	"dustbe/database"
	"dustbe/util"
	"html/template"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func SignUp(c *gin.Context) {
	ok := util.LimitIpInterval(c, 2)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "你刚刚已经注册过了，再过一段时间再来吧！"})
		return
	}
	name := c.Query("name")
	name = template.HTMLEscapeString(name)

	password := c.Query("password")
	imgUrl := c.Query("imgUrl")
	
	dustUser, err := database.SignUp(name, password, imgUrl)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}
	dustUser.HashedPassword = ""

	// 设置 session
	session := sessions.Default(c)
	session.Set("user", name)
	err = session.Save()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "保存用户信息失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": dustUser})
}